package com.scsj.supermarket.view.activity.city;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.scsj.supermarket.R;
import com.scsj.supermarket.base.SelectAllCityBase;
import com.scsj.supermarket.bean.SelectAllCityBean;
import com.scsj.supermarket.config.RxSPConfig;
import com.scsj.supermarket.presenter.SelectAllCityPresenter;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.vondear.rxtools.RxSPTool;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * 地址选择
 */

public class SelectCityActivity extends BaseActivity implements SelectAllCityBase.IView, View.OnClickListener {


    private CityListAdapter mCityListAdapter;
    private ExpandableListView mCityListView;
    private PingyinAdapter<SelectAllCityBean.DataBean.ListBean> mProfessionalListAdapter;
    private EditText mSearch;
    private List<SelectAllCityBean.DataBean.ListBean> mCityBean;
    private TextView mCurrent_city;
    public BDLocationListener myListener1 = new MyLocationListener1();
    private RelativeLayout nullLayout;
    private String current_city = "";
    private boolean isLocation = false;
    public LocationClient mLocationClient = null;
    private SelectAllCityPresenter presenter;
    private BDLocation mLocation;
    private ImageView back;
    private TextView title;



    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_select_city);
        presenter = new SelectAllCityPresenter(this);
        initView();
        getAreaInfo();
        FancyIndexer mFancyIndexer = (FancyIndexer) findViewById(R.id.bar);
        mFancyIndexer.setOnTouchLetterChangedListener(new FancyIndexer.OnTouchLetterChangedListener() {

            @Override
            public void onTouchLetterChanged(String letter) {
                try {
                    for (int i = 0, j = mProfessionalListAdapter.getKeyMapList().getTypes().size(); i < j; i++) {
                        String str = mProfessionalListAdapter.getKeyMapList().getTypes().get(i);
                        if (letter.toUpperCase().equals(str.toUpperCase())) {
                            /**跳转到选中的字母表*/
                            mCityListView.setSelectedGroup(i);
                        }
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }

            }
        });
        mSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    if (!TextUtils.isEmpty(mSearch.getText().toString())) {
                        if (mCityBean != null) {
                            ArrayList<SelectAllCityBean.DataBean.ListBean> searchList = new ArrayList<SelectAllCityBean.DataBean.ListBean>();
                            for (SelectAllCityBean.DataBean.ListBean city : mCityBean) {
                                if (city.getDistrict().getName().contains(mSearch.getText().toString())) {
                                    searchList.add(city);
                                }

                            }
                            if (searchList.size() > 0) {
                                mProfessionalListAdapter.listToKeyMapList(searchList);
                                mProfessionalListAdapter.notifyDataSetChanged();
                            } else {
                                mCityListView.setVisibility(View.GONE);
                                nullLayout.setVisibility(View.VISIBLE);
                            }

                        }
                    } else {
                        if (mCityBean != null) {
                            mProfessionalListAdapter.listToKeyMapList(mCityBean);
                            mProfessionalListAdapter.notifyDataSetChanged();
                            /**展开并设置adapter*/
                            mProfessionalListAdapter.expandGroup();
                        }
                    }
                    return true;
                }
                return false;
            }
        });
        mSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if(!TextUtils.isEmpty(s.toString())){
//                    if(mCityBean != null){
//                        ArrayList<City> searchList = new ArrayList<City>();
//                        for (City city  : mCityBean.getData()){
//                               if(city.getName().contains(s.toString())){
//                                   searchList.add(city);
//                               }
//
//                        }
//                        if(searchList.size()>0){
//                            mProfessionalListAdapter.listToKeyMapList(searchList);
//                            mProfessionalListAdapter.notifyDataSetChanged();
//                        }
//
//                    }
//                }else {
//                    if(mCityBean != null){
//                        mProfessionalListAdapter.listToKeyMapList(mCityBean.getData());
//                        mProfessionalListAdapter.notifyDataSetChanged();
//                        /**展开并设置adapter*/
//                        mProfessionalListAdapter.expandGroup();
//                    }
//                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

//        List<CityBean> list = new ArrayList<>();
//        for (int i=0;i<type.length;i++){
//            CityBean professionalBean = new CityBean();
//            professionalBean.setName(type[i]);
//            list.add(professionalBean);
//        }
    }

    private void doLocation() {
        Log.e("TAG", "doLocation");
        mLocationClient = new LocationClient(this);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener1);
        initLocation1();
        //注册监听函数
        if (mLocationClient.isStarted()) {
            mLocationClient.requestLocation();
        } else {
            mLocationClient.start();
            mLocationClient.requestLocation();
        }
    }

    private void initLocation1() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span = 1000 * 60 * 5;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }

    @Override
    protected void initView() {

        back = (ImageView) findViewById(R.id.back);
        mCityListView = (ExpandableListView) findViewById(R.id.listview);
        title = (TextView) findViewById(R.id.title);
        title.setText("选择城市");
        mSearch = (EditText) findViewById(R.id.search);
        mCurrent_city = (TextView) findViewById(R.id.current_city);
        mCurrent_city.setText("当前定位城市:  定位中···");
        nullLayout = (RelativeLayout) findViewById(R.id.null_layout);
        doLocation();
    }

    @Override
    protected void initListener() {
        back.setOnClickListener(this);
        mCurrent_city.setOnClickListener(this);

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                hinKkeyboard(v);
                finish();
                break;
            case R.id.current_city:
                if (isLocation) {
                    if (!TextUtils.isEmpty(current_city)) {
                        Intent intent = new Intent();
                        intent.putExtra("name", current_city);
                        setResult(1, intent);
//                        Tool.setStringShared(SelectCityActivity.this, "city", current_city);
                        RxSPTool.putString(SelectCityActivity.this, RxSPConfig.CITY, current_city);
                        finish();
                    } else {
//                        ToastUtils.showToast(context, "定位中···");
                        Toasty.normal(this, "定位中···").show();
                    }
                } else {
//                    ToastUtils.showToast(context, "定位失败");
                    Toasty.normal(this, "定位失败").show();
                }
                break;
        }
    }


    private void getAreaInfo() {

        com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), object.toString());
        presenter.deliverData(body);

    }


    @Override
    public void showSuccessMsg(String s, SelectAllCityBean selectAllCityBean) {
//        mCityBean = new Gson().fromJson(result, CityBean.class);
        if (selectAllCityBean.getData() != null) {
            mCityBean = selectAllCityBean.getData().getList();
            /**加入支持泛型*/
            mProfessionalListAdapter = new PingyinAdapter<SelectAllCityBean.DataBean.ListBean>(mCityListView, selectAllCityBean.getData().getList(), R.layout.city_item) {

                @Override
                public String getItemName(SelectAllCityBean.DataBean.ListBean goodMan) {
                    return goodMan.getDistrict().getName();
                }

                /**返回viewholder持有*/
                @Override
                public ViewHolder getViewHolder(SelectAllCityBean.DataBean.ListBean goodMan) {
                    /**View holder*/
                    class DataViewHolder extends ViewHolder implements View.OnClickListener {
                        public TextView tv_name;

                        public DataViewHolder(SelectAllCityBean.DataBean.ListBean goodMan) {
                            super(goodMan);
                        }

                        /**初始化*/
                        @Override
                        public ViewHolder getHolder(View view) {
                            tv_name = (TextView) view.findViewById(R.id.city_name);
                            /**在这里设置点击事件*/
                            view.setOnClickListener(this);

                            return this;
                        }

                        /**显示数据*/
                        @Override
                        public void show() {
                            tv_name.setText(getItem().getDistrict().getName());

                        }

                        /**点击事件*/
                        @Override
                        public void onClick(View v) {
//                        Uri uri = Uri.parse("tel:"+getItem().getPhone());
//                        Intent intent2 = new Intent(Intent.ACTION_DIAL, uri);
//                        startActivity(intent2);
//									Toast.makeText(v.getContext(),getItem().getName(),Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.putExtra("name", getItem().getDistrict().getName());
                            setResult(1, intent);
//                            Tool.setStringShared(SelectCityActivity.this, "city", getItem().getName());
                            RxSPTool.putString(SelectCityActivity.this, RxSPConfig.CITY, getItem().getDistrict().getName());
                            hinKkeyboard(v);
                            finish();
                        }
                    }
                    return new DataViewHolder(goodMan);
                }

                @Override
                public void onItemClick(SelectAllCityBean.DataBean.ListBean goodMan, View view, int position) {
//                Toast.makeText(view.getContext(),position+" "+goodMan.getName(),Toast.LENGTH_SHORT).show();
                }
            };
            /**展开并设置adapter*/
            mProfessionalListAdapter.expandGroup();

        }
    }

    @Override
    public void showErrorMsg(String s) {

    }

    public class MyLocationListener1 implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //获取定位结果
            StringBuffer sb = new StringBuffer(256);

            sb.append("time : ");
            sb.append(location.getTime());    //获取定位时间

            sb.append("\nerror code : ");
            sb.append(location.getLocType());    //获取类型类型

            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());    //获取纬度信息

            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());    //获取经度信息

            sb.append("\nradius : ");
            sb.append(location.getRadius());    //获取定位精准度

            if (location.getLocType() == BDLocation.TypeGpsLocation) {

                // GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());    // 单位：公里每小时

                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());    //获取卫星数

                sb.append("\nheight : ");
                sb.append(location.getAltitude());    //获取海拔高度信息，单位米

                sb.append("\ndirection : ");
                sb.append(location.getDirection());    //获取方向信息，单位度

                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {

                // 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());    //获取地址信息

                sb.append("\noperationers : ");
                sb.append(location.getOperators());    //获取运营商信息

                sb.append("\ndescribe : ");
                sb.append("网络定位成功");

            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {

                // 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");

            } else if (location.getLocType() == BDLocation.TypeServerError) {

                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");

            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {

                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");

            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {

                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");

            }

            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());    //位置语义化信息

            List<Poi> list = location.getPoiList();    // POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            mLocation = location;
            if (location != null && !TextUtils.isEmpty(location.getCity())) {
                isLocation = true;
                mCurrent_city.setText("当前定位城市: " + mLocation.getCity());
                current_city = mLocation.getCity();
            } else {
                isLocation = false;
//                ToastUtils.showToast(context, "定位失败");
                Toasty.error(SelectCityActivity.this, "定位失败").show();
            }
//            MyLog.e("MainFragment", sb.toString());
            mLocationClient.stop();
        }
    }

    public void hinKkeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }
}
